"""
@Project ：HaloInterfaceProject 
@File    ：WebCookie.py
@IDE     ：PyCharm 
@Author  ：张成龙
@Date    ：2024/10/23 10:45 
@explain ：
"""
import os
import time

from dotenv import load_dotenv, set_key
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.edge.options import Options
from selenium.webdriver.edge.service import Service
from webdriver_manager.microsoft import EdgeChromiumDriverManager

from conftest import BASE_DIR
from utils.LoadEnvUtil import LoadEnvUtil


class WebCookie:

    @classmethod
    def get_cookies(cls):
        # 创建 EdgeOptions 对象
        # 创建 WebDriver 实例
        options = Options()
        options.add_argument('--headless')
        driver = webdriver.Edge(service=Service(EdgeChromiumDriverManager().install()), options=options)
        driver.implicitly_wait(10)
        driver.get(LoadEnvUtil.get_env_params("BASE_URL") + "/console/login")
        driver.find_element(By.ID, "username").send_keys("admin")
        driver.find_element(By.ID, "plainPassword").send_keys("admin")

        driver.find_element(By.XPATH, "//*[@id='login-form']/div[4]/button").click()
        time.sleep(1)
        cookies = driver.get_cookies()
        time.sleep(1)
        print(cookies)
        # 获取 session 值
        session_value = cookies[0]["value"]
        print("SESSION=", session_value)

        # 检查 .env 文件是否存在，如果不存在则创建
        env_file = BASE_DIR + os.sep + '.env'
        LoadEnvUtil.set_env_params(env_file, 'SESSION', session_value)
        time.sleep(1)


if __name__ == '__main__':
    WebCookie.get_cookies()